package com.woniu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.client.AccountClient;
import com.woniu.commons.exception.YogaException;
import com.woniu.commons.model.StateData;
import com.woniu.dao.mapper.YClassTypeMapper;
import com.woniu.dao.mapper.YPersonalClassMapper;
import com.woniu.dao.mapper.YUserPersonalClassMarginMapper;
import com.woniu.model.YCoach;
import com.woniu.model.YUser;
import com.woniu.model.dto.*;
import com.woniu.model.form.AddPersonalClassMarginForm;
import com.woniu.model.form.UserAndClassIdForm;
import com.woniu.model.model.YClassType;
import com.woniu.model.model.YPersonalClass;
import com.woniu.model.model.YUserLeagueClassMargin;
import com.woniu.model.model.YUserPersonalClassMargin;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.model.param.UserByMyPersonalParam;
import com.woniu.service.YUserPersonalClassMarginService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@Service
public class YUserPersonalClassMarginServiceImpl extends ServiceImpl<YUserPersonalClassMarginMapper, YUserPersonalClassMargin> implements YUserPersonalClassMarginService {

    @Resource
    private YPersonalClassMapper personalClassMapper;
    @Resource
    private AccountClient accountClient;
    @Resource
    private YClassTypeMapper classTypeMapper;


    @Override
    public Integer addPersonalClassMargin(AddPersonalClassMarginForm form) {
        YUserPersonalClassMargin userPersonalClassMargin = baseMapper.selectOne(new QueryWrapper<YUserPersonalClassMargin>().eq("personal_class_id", form.getPersonalClassId()).eq("user_id", form.getUserId()));
        Integer i =0;
        if (userPersonalClassMargin == null){
            YUserPersonalClassMargin margin = new YUserPersonalClassMargin();
            margin.setOrderNum(form.getOrderNum());
            margin.setPersonalClassId(form.getPersonalClassId());
            margin.setUserId(form.getUserId());
            margin.setMarginNum(form.getMarginNum());
            margin.setCoachId(personalClassMapper.selectById(form.getPersonalClassId()).getCoachId());

            i = baseMapper.insert(margin);
        }else {
            userPersonalClassMargin.setMarginNum(userPersonalClassMargin.getMarginNum()+form.getMarginNum());
            userPersonalClassMargin.setPersonalClassId(form.getPersonalClassId());
            i = baseMapper.updateById(userPersonalClassMargin);
        }
        return i;
    }

    @Override
    public YUserPersonalClassMargin loadPersonalMarginByUserAndClassId(UserAndClassIdForm form) {
        YUserPersonalClassMargin userPersonalClassMargin = baseMapper.selectOne(new QueryWrapper<YUserPersonalClassMargin>().eq("user_id", form.getUserId()).eq("coach_id", form.getCoachId()));
        if (userPersonalClassMargin == null){
            throw new YogaException(3302,"该课程余量对象不存在");
        }

        return userPersonalClassMargin;
    }

    @Override
    public void substractPersonalMarginByUserAndClassId(Integer id) {
        YUserPersonalClassMargin margin = baseMapper.selectById(id);
        if (margin == null){
            throw new YogaException(3307,"该课程余量不存在");
        }
        if (margin.getMarginNum() == 0){
            throw new YogaException(3308,"该课程余量不足");
        }
        margin.setMarginNum(margin.getMarginNum() - 1);
        baseMapper.updateById(margin);
    }

    @Override
    public List<Integer> loadPersonalStudentIds(Integer coachId) {
        List<YUserPersonalClassMargin> margins = baseMapper.selectList(new QueryWrapper<YUserPersonalClassMargin>().eq("coach_id", coachId).ne("margin_num", 0));
        List<Integer> collect = margins.stream().map(o -> o.getUserId()).collect(Collectors.toList());

        return collect;
    }

    @Override
    public List<StudentDto> loadPersonalStudent(Integer coachId) {
        List<YUserPersonalClassMargin> margins = baseMapper.selectList(new QueryWrapper<YUserPersonalClassMargin>().eq("coach_id", coachId).ne("margin_num", 0));
        ArrayList<StudentDto> studentDtos = new ArrayList<>();
        for (YUserPersonalClassMargin m:margins
             ) {
            YUser user = accountClient.loadUsersByIds(m.getUserId()).getData();
            StudentDto studentDto = BeanUtil.toBean(user, StudentDto.class);
            studentDto.setMargin(m);
            studentDtos.add(studentDto);
        }
//        List<Integer> collect = margins.stream().map(o -> o.getUserId()).collect(Collectors.toList());
        return studentDtos;
    }

    @Override
    public List<UserPersonalClassMarginDto> loadPersonalClassByCoachId(Integer coachId) {
        List<YUserPersonalClassMargin> margins = baseMapper.selectList(new QueryWrapper<YUserPersonalClassMargin>().eq("personal_class_state", StateData.PERSONAL_CLASS_STATE_NOT_OK).eq("coach_id", coachId));

        ArrayList<UserPersonalClassMarginDto> dtos = new ArrayList<>();
        for (YUserPersonalClassMargin m:margins
             ) {
            UserPersonalClassMarginDto d = new UserPersonalClassMarginDto();
            d.setMargin(m);
            d.setUserNickname(accountClient.loadUsersByIds(m.getUserId()).getData().getUserNickname());
            dtos.add(d);
        }
        return dtos;
    }


    /**
     * 通过用户token查该用户的私课
     *
     * @param param
     * @return
     */
    @Override
    public Page<UserByMyPersonalDto> userByMyPersonal(UserByMyPersonalParam param) throws YogaException {

        if (param.getPageNum() == null) {
            param.setPageNum(1);
        }
        if (param.getPageSize() == null) {
            param.setPageSize(5);
        }

        QueryWrapper<YUserPersonalClassMargin> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", param.getUserId());
        Page<YUserPersonalClassMargin> personalClassMarginPage = baseMapper.selectPage(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);

        Page<UserByMyPersonalDto> page = new Page<>();
        page.setCurrent(personalClassMarginPage.getCurrent());
        page.setOptimizeCountSql(personalClassMarginPage.optimizeCountSql());
        page.setPages(personalClassMarginPage.getPages());
        page.setSearchCount(personalClassMarginPage.searchCount());
        page.setSize(personalClassMarginPage.getSize());
        page.setTotal(personalClassMarginPage.getTotal());

        ArrayList<UserByMyPersonalDto> dto = new ArrayList<>();

        for (YUserPersonalClassMargin userPersonalClassMargin:personalClassMarginPage.getRecords()){

            UserByMyPersonalDto pageDto = BeanUtil.toBean(userPersonalClassMargin, UserByMyPersonalDto.class);

            //通过教练ID查出教练对象
            YCoach yCoach = accountClient.byId(userPersonalClassMargin.getCoachId()).getData();
            if (yCoach == null){
                throw new YogaException(500,"请先招募教练");
            }

            pageDto.setCoachName(yCoach.getCoachName());
            pageDto.setCoachPhone(yCoach.getCoachPhone());
            pageDto.setCoachImage(yCoach.getCoachImage());

            dto.add(pageDto);
        }
        page.setRecords(dto);

        return page;
    }




    /**
     * 通过用户token查该用户的私课后，点击打开这个私课的详细信息
     *
     * @param
     * @return
     */
    @Override
    public UserByMyPersonalBaseDto userByMyPersonalBase(Integer userId) {
        QueryWrapper<YUserPersonalClassMargin> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<YUserPersonalClassMargin> list = baseMapper.selectList(wrapper);
        System.out.println(list);

        // 提取 personal_class_id 和 coach_id
        List<Integer> personalClassIds = list.stream().map(YUserPersonalClassMargin::getPersonalClassId).collect(Collectors.toList());
        List<Integer> coachIds = list.stream().map(YUserPersonalClassMargin::getCoachId).collect(Collectors.toList());
        List<Integer> ids = list.stream().map(YUserPersonalClassMargin::getId).collect(Collectors.toList());
        List<String> orderNums = list.stream().map(YUserPersonalClassMargin::getOrderNum).collect(Collectors.toList());
        List<Integer> pcIs = list.stream().map(YUserPersonalClassMargin::getPersonalClassId).collect(Collectors.toList());
        List<Integer> marginNums = list.stream().map(YUserPersonalClassMargin::getMarginNum).collect(Collectors.toList());


        System.out.println(personalClassIds);
        System.out.println(coachIds);

        UserByMyPersonalBaseDto baseDto = new UserByMyPersonalBaseDto();
        baseDto.setUserId(userId);
        for (Integer id:ids){
            baseDto.setId(id);
        }
        for (String ons :orderNums){
            baseDto.setOrderNum(ons);
        }
        for (Integer pc:pcIs){
            baseDto.setPersonalClassId(pc);
        }
        for (Integer mn:marginNums){
            baseDto.setMarginNum(mn);
        }

        for (Integer personalClassId : personalClassIds) {
            YPersonalClass yPersonalClass = personalClassMapper.selectById(personalClassId);

            if (yPersonalClass == null) {
                throw new YogaException(500, "课程不存在");
            }

            // 通过课程类型id查出课程类型名字
            YClassType yClassType = classTypeMapper.selectById(yPersonalClass.getClassTypeId());
            if (yClassType == null) {
                throw new YogaException(500, "课程类型不存在");
            }

            // 设置课程相关信息

            baseDto.setPrice(yPersonalClass.getPrice());
            baseDto.setMinute(yPersonalClass.getMinute());
            baseDto.setPersonalClassState(yPersonalClass.getPersonalClassState());
            baseDto.setScore(yPersonalClass.getScore());
            baseDto.setClassTypeId(yPersonalClass.getClassTypeId());
            baseDto.setClassTypeName(yClassType.getClassTypeName());
        }

        for (Integer coachId : coachIds) {
            YCoach yCoach = accountClient.byId(coachId).getData();
            if (yCoach == null) {
                throw new YogaException(500, "教练不存在");
            }

            // 设置教练相关信息
            baseDto.setCoachPhone(yCoach.getCoachPhone());
            baseDto.setCoachName(yCoach.getCoachName());
            baseDto.setCoachImage(yCoach.getCoachImage());
            baseDto.setCoachId(coachId);
        }

        return baseDto;
    }

//    @Override
//    public UserByMyPersonalBaseDto userByMyPersonalBase(Integer userId) {
//        QueryWrapper<YUserPersonalClassMargin> wrapper = new QueryWrapper<>();
//        wrapper.eq("user_id",userId);
//        List<YUserPersonalClassMargin> list = baseMapper.selectList(wrapper);
//        System.out.println(list);
//        // 提取 personal_class_id
//        List<Integer> personalClassIds = list.stream().map(YUserPersonalClassMargin::getPersonalClassId).collect(Collectors.toList());
//        System.out.println(personalClassIds);
//
//        // 提取 coach_id
//        List<Integer> coachIds = list.stream().map(YUserPersonalClassMargin::getCoachId).collect(Collectors.toList());
//        System.out.println(coachIds);
//
//        UserByMyPersonalBaseDto baseDto = BeanUtil.toBean(list, UserByMyPersonalBaseDto.class);
//        // 处理每个 personal_class_id
//        for (Integer personalClassId : personalClassIds) {
//            YPersonalClass yPersonalClass = personalClassMapper.selectById(personalClassId);
//
//            for (Integer coachId :coachIds){
//                //通过教练ID查出教练对象
//                YCoach yCoach = accountClient.byId(coachId).getData();
//                if (yCoach == null){
//                    throw new YogaException(500,"请先招募教练");
//                }
//
//
//                YClassType yClassType = classTypeMapper.selectById(yPersonalClass.getClassTypeId());
//
//                baseDto.setCoachPhone(yCoach.getCoachPhone());
//                baseDto.setCoachName(yCoach.getCoachName());
//                baseDto.setCoachImage(yCoach.getCoachImage());
//                baseDto.setCoachId(yCoach.getCoachId());
//                baseDto.setPrice(yPersonalClass.getPrice());
//                baseDto.setMinute(yPersonalClass.getMinute());
//                baseDto.setPersonalClassState(yPersonalClass.getPersonalClassState());
//                baseDto.setScore(yPersonalClass.getScore());
//                baseDto.setClassTypeId(yPersonalClass.getClassTypeId());
//                baseDto.setClassTypeName(yClassType.getClassTypeName());
//            }
//        }
//
//        return baseDto;
//    }




}
